package com.example.springbootredis.service.impl;


import com.example.springbootredis.entiy.News;
import com.example.springbootredis.repository.NewsRepository;
import com.example.springbootredis.service.NewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class NewsServiceImpl implements NewsService {

    private final NewsRepository newsRepository;
    private final ElasticsearchOperations elasticsearchOperations;

    @Override
    public News save(News news) {
        return newsRepository.save(news);
    }

    @Override
    public Optional<News> findById(String id) {
        return newsRepository.findById(id);
    }

    @Override
    public void deleteById(String id) {
        newsRepository.deleteById(id);
    }

    @Override
    public List<News> findAll() {
        return (List<News>) newsRepository.findAll();
    }

    @Override
    public List<News> search(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return findAll();
        }

        Criteria criteria = new Criteria("title").matches(keyword)
                .or(new Criteria("content").matches(keyword));
        CriteriaQuery query = new CriteriaQuery(criteria);

        SearchHits<News> searchHits = elasticsearchOperations.search(query, News.class);

        return searchHits.getSearchHits()
                .stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
    }
}